package com.git.hui.yinshua.biz.banner.dao.repository;

import com.git.hui.yinshua.api.model.constants.GlobalConstants;
import com.git.hui.yinshua.biz.banner.dao.entity.BannerEntity;
import com.git.hui.yinshua.biz.banner.dao.mapper.BannerMapper;
import com.git.hui.yinshua.biz.rest.models.banner.req.BannerReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author YiHui
 * @date 2024/6/17
 */
@Repository
public class BannerRepository {
    @Autowired
    private BannerMapper bannerMapper;

    public BannerEntity saveBanner(BannerReq req) {
        BannerEntity entity = new BannerEntity();
        entity.setTitle(req.getTitle() == null ? "" : req.getTitle());
        entity.setIntro(req.getIntro() == null ? "" : req.getIntro());
        entity.setState(req.getState() == null ? GlobalConstants.ONLINE_STATE : GlobalConstants.OFFLINE_STATE);
        entity.setTab(req.getTab());
        entity.setImg(req.getImg());
        entity.setImgColor(req.getImgColor() == null ? "#ffffff" : req.getImgColor());
        entity.setSort(req.getSort() == null ? 1 : req.getSort());
        if (req.getLinkType() != null) {
            entity.setUrl(req.getLinkType().buildUrl(req.getLink()));
        } else {
            entity.setUrl("");
        }
        bannerMapper.saveBanner(entity);
        return entity;
    }

    public boolean updateBanner(BannerReq req) {
        BannerEntity entity = new BannerEntity();
        entity.setId(req.getBannerId());
        entity.setTitle(req.getTitle());
        entity.setIntro(req.getIntro());
        entity.setState(req.getState());
        entity.setTab(req.getTab());
        entity.setImg(req.getImg());
        entity.setImgColor(req.getImgColor());
        if (req.getLinkType() == null) {
            entity.setUrl(null);
        } else {
            entity.setUrl(req.getLinkType().buildUrl(req.getLink()));
        }
        entity.setSort(req.getSort());
        return bannerMapper.updateBanner(entity) > 0;
    }

    public boolean online(Integer bannerId, boolean online) {
        BannerEntity entity = new BannerEntity();
        entity.setId(bannerId);
        entity.setState(online ? GlobalConstants.ONLINE_STATE : GlobalConstants.OFFLINE_STATE);
        return bannerMapper.updateBanner(entity) > 0;
    }

    public boolean deleteBanner(Integer bannerId) {
        return bannerMapper.delete(bannerId) > 0;
    }

    public List<BannerEntity> bannerList(BannerReq req) {
        return bannerMapper.listBanners(req);
    }

    public List<BannerEntity> queryForTab(Integer tab) {
        return bannerMapper.queryByTab(tab);
    }

    public int count(BannerReq req) {
        return bannerMapper.count(req);
    }
}
